package com.ruiysoft.crm.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ruiysoft.crm.dto.CustomerEx;
import com.ruiysoft.crm.entity.Customer;
import com.ruiysoft.crm.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    CustomerMapper customerMapper;

    @PostMapping("create")
    public Object create(@RequestBody Customer customer, Integer createrId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            customer.setCreateTime(new Date());
            customer.setUpdateTime(new Date());
            customer.setCreater(createrId);

            if (customerMapper.insert(customer) > 0)
                map.put("success", true);

        } catch (Exception error) {
            map.put("errorMsg", "create 异常: " + error.getMessage());
        }

        return map;
    }

    @GetMapping("delete")
    public Object delete(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            if (customerMapper.deleteById(id) > 0)
                map.put("success", true);

        } catch (Exception error) {
            map.put("errorMsg", "delete 异常: " + error.getMessage());
        }

        return map;
    }

    @PostMapping("edit")
    public Object edit(@RequestBody Customer customer) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            if (customerMapper.updateById(customer) > 0)
                map.put("success", true);
            else
                map.put("errorMsg", "更新失败!");

        } catch (Exception error) {
            map.put("errorMsg", "create 异常: " + error.getMessage());
        }

        return map;
    }

    @Cacheable("query")
    @GetMapping("query")
    public Object query() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            EntityWrapper<Customer> entityWrapper = new EntityWrapper();
//            List<Customer> list = customerMapper.selectPage(new Page<Customer>(1, 25), entityWrapper);
            List<CustomerEx> list = customerMapper.selectLeftJoinEmployeeValueList();
            if(list.size() > 0) {
                map.put("success", true);
                map.put("data", list);
            }
            else
                map.put("errorMsg", "查询数据失败");

        } catch (Exception error) {
            map.put("errorMsg", "delete 异常: " + error.getMessage());
        }

        return map;
    }


}
